package com.howie.parnote.jms.sender;

import com.howie.parnote.util.LogUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.*;

/**
 * <p>Title: parnote</p>
 * <p>
 * Description: parnote
 * </p>
 *
 * @author huangyan
 *         Created by HY on 2015/4/18 0018.
 * @version v1.0.0
 */
public abstract class AbstractMessageSender implements ConfigurableMessageSender {

	private static final Logger logger = LogUtil.getLogger(AbstractMessageSender.class);

	@Autowired
	private ConnectionFactory connectionFactory;

	@Override
	public void handleMessage() {
		try {
			if (logger.isDebugEnabled()) {
				logger.debug("进入消息发送准备阶段");
			}
			Connection connection = connectionFactory.createConnection();
			connection.start();
			Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			Destination destination = createDestination(session);
			MessageProducer producer = session.createProducer(destination);
			Message message = createMessage(session);
			producer.send(message);
			//只有commit之后，消息才会进入队列
			session.commit();
			session.close();
			connection.close();
		} catch (JMSException e) {
			logger.error("消息发送handleMessage出现错误:" + e.getMessage(), e);
		}
	}

	protected abstract Message createMessage(Session session) throws JMSException;

	protected abstract Destination createDestination(Session session) throws JMSException;

}
